package com.jirefox.loner.daemon.service;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import com.jirefox.loner.daemon.model.AppInstance;
import com.jirefox.loner.daemon.model.WorkDir;
import com.jirefox.loner.runtime.RuntimeStarter;

@Service
public class AppService {

	private final Logger logger = LoggerFactory.getLogger(AppService.class);

	private Map<String, AppInstance> store = new HashMap<String, AppInstance>();

	@Autowired
	private WorkDir workDir;

	public void startApp(File appFolder) {
		Set<String> runtimeArgsSet = new HashSet<String>();
		String driverFolder = workDir.driversDir();
		runtimeArgsSet.add("--loner.appDir=" + appFolder.getAbsolutePath());
		runtimeArgsSet.add("--loner.driversDir=" + driverFolder);
		runtimeArgsSet.add("--spring.config.location=" + appFolder.getAbsolutePath() + "/app.yml");
		String[] runtimeArgs = runtimeArgsSet.toArray(new String[runtimeArgsSet.size()]);

		AppInstance appInstance = new AppInstance();
		SpringApplication runtimeApplication = new SpringApplication(RuntimeStarter.class);
		ConfigurableApplicationContext context = runtimeApplication.run(runtimeArgs);
		appInstance.setApplication(runtimeApplication);
		appInstance.setContext(context);

		store.put(appFolder.getName(), appInstance);
	}

}
